package com.jrx.anytxn.param.controller.aviator;

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.jrx.anytxn.i18n.response.TxnPage;
import com.jrx.anytxn.i18n.response.TxnRespResult;
import com.jrx.anytxn.common.exception.TxnRuntimeException;
import com.jrx.anytxn.param.dto.aviator.RequestRulePageReq;
import com.jrx.anytxn.param.dto.aviator.RuleReq;
import com.jrx.anytxn.param.dto.aviator.RuleRes;
import com.jrx.anytxn.param.plugins.DeleteLog;
import com.jrx.anytxn.param.plugins.DeleteLogHelper;
import com.jrx.anytxn.param.service.aviator.IRuleService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import jrx.auth.filter.service.InfoService;
import org.apache.commons.lang.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.ArrayList;
import java.util.List;


/**
 * 规则管理api
 *
 * @author zhangyingxuan
 * @date 2018-08-27
 **/
@RequestMapping("/param/rule")
@RestController
@Api(tags = "规则管理api")
public class RuleController {
    private static final Logger logger = LoggerFactory.getLogger(RuleController.class);
    @Autowired
    private IRuleService ruleService;
    @Autowired
    private InfoService infoService;


    /**
     * 添加规则
     *
     * @param req 请求参数对象
     * @return ResponseDTO
     */
    @ApiOperation(value = "添加规则")
    @PostMapping(value = "/addRule")
    @JsonIgnoreProperties
    public TxnRespResult register(@RequestBody RuleReq req) {
        logger.info("RuleController register start");
        req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
        req.setCreateBy(infoService.getUser().getUserName());
        req.setUpdateBy(infoService.getUser().getUserName());
        ruleService.registerRule(req);
        logger.info("RuleController register end");
        return new TxnRespResult<>().getSuccess("添加规则成功");
    }

    /**
     * 更新规则
     *
     * @param req 请求参数对象
     * @return ResponseDTO
     */
    @ApiOperation(value = "更新规则")
    @PutMapping(value = "/modifyRule")
    @JsonIgnoreProperties
    public TxnRespResult modifyRule(@RequestBody RuleReq req) {
        logger.info("RuleController modify start");
        req.setUpdateBy(infoService.getUser().getUserName());
        ruleService.modifyRule(req);
        logger.info("RuleController modify end");
        return new TxnRespResult<>().getSuccess("更新规则成功");
    }


    /**
     * 根据ID或者ruleType 规则类型删除规则
     *
     * @param id , ruleType
     * @return ResponseDTO
     */
    @ApiOperation(value = "根据ID或者ruleType删除规则")
    @DeleteMapping(value = "/rules")
    public TxnRespResult cancelByIdOrRuleType(@RequestParam(value = "id", required = false) Long id, @RequestParam(value = "ruleType", required = false) String ruleType,@RequestParam(value = "tenantId", required = false) String tenantId,@RequestParam(value = "organizationNumber",required = false)String organizationNumber) {
        TxnRespResult result = new TxnRespResult();
        logger.info("RuleController cancelByIdOrRuleType start");
        RuleRes req = new RuleRes();
        req.setId(id);
        req.setRuleType(ruleType);
        req.setOrganizationNumber(organizationNumber);
        req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));

        DeleteLog deleteLog = new DeleteLog(infoService.getUser().getUserName());
        DeleteLogHelper.setDelleteHistory(deleteLog);
        try {
            ruleService.cancelByIdOrRuleType(req);
            result = result.getSuccess(null);
        } catch (TxnRuntimeException e) {
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            logger.error(e.getMessage(), e);
        } finally {
            DeleteLogHelper.clearLocalHistory();
        }
        logger.info("RuleController cancelByIdOrRuleType end");
        return result;
    }

    /**
     * 根据productNumber 规则类型删除规则
     *
     * @param productNumber
     * @return ResponseDTO
     */
    @ApiOperation(value = "根据产品num删除规则")
    @DeleteMapping(value = "/rules/{productNumber}")
    public TxnRespResult cancelByProductNumber(@PathVariable(value = "productNumber", required = false) String productNumber) {
        TxnRespResult result = new TxnRespResult();
        logger.info("RuleController cancelByProductNumber start");
        if (StringUtils.isBlank(productNumber)) {
            productNumber = null;
        }
        RuleReq req = new RuleReq();
        req.setProductNumber(productNumber);
        req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
        try {
            ruleService.cancelByIdOrRuleType(req);
            result = result.getSuccess(null);
        } catch (TxnRuntimeException e) {
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            logger.error(e.getMessage(), e);
        }
        logger.info("RuleController cancelByProductNumber end");
        return result;
    }

    /**
     * 根据规则ID或者规则类型查询规则
     *
     * @param id                 ID
     * @param ruleType           规则类型
     * @param productNumber      产品id
     * @param organizationNumber 机构号
     * @return ResponseDTO
     */
    @ApiOperation(value = "获取规则信息")
    @GetMapping(value = "/rules/{id}/{ruleType}/{tenantId}")
    public TxnRespResult getRuleByIdOrRuleType(@PathVariable(value = "id", required = false) Long id, @PathVariable(value = "ruleType", required = false) String ruleType, @RequestParam(value = "productNumber", required = false) String productNumber, @RequestParam(value = "organizationNumber", required = false) String organizationNumber,@PathVariable(value = "tenantId") String tenantId) {
        TxnRespResult<ArrayList<RuleRes>> result = new TxnRespResult();
        logger.info("RuleController getRuleByIdOrRuleType start");
        if (StringUtils.isBlank(productNumber)) {
            productNumber = null;
        }
        RuleReq req = new RuleReq();
        req.setId(id);
        req.setRuleType(ruleType);
        req.setOrganizationNumber(organizationNumber);
        req.setProductNumber(productNumber);
        req.setTenantId(String.valueOf(infoService.getUser().getProjectId()));
        try {
            List<RuleRes> resultList = ruleService.getByIdAndTenIdAndType(req);
            result = result.getSuccess((ArrayList<RuleRes>) resultList);
        } catch (TxnRuntimeException e) {
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            logger.error(e.getMessage(), e);
        }
        logger.info("RuleController getRuleByIdOrRuleType end");
        return result;
    }


    /**
     * 分页查询规则列表
     *
     * @return ResponseDTO 分页的规则列表
     */

    @ApiOperation(value = "分页查询规则列表")
    @GetMapping(value = "/rules")
    @JsonIgnoreProperties
    public TxnRespResult getPageByRuleSetTypeName(@RequestParam(defaultValue = "1") Integer page, @RequestParam(defaultValue = "10") Integer rows, @RequestParam(value = "productNumber", required = false) String productNumber, @RequestParam(value = "ruleType", required = false) String ruleType, @RequestParam(value = "organizationNumber", required = false) String organizationNumber,@RequestParam("ruleId") String ruleId) {

        logger.info("RuleController getPageByRuleSetTypeName start");
        TxnRespResult<TxnPage<RuleRes>> result = new TxnRespResult();

        try {
            String tenantId=String.valueOf(infoService.getUser().getProjectId());
            RequestRulePageReq requestRulePageDTO = new RequestRulePageReq();
            requestRulePageDTO.setRuleType(ruleType);
            requestRulePageDTO.setOrganizationNumber(organizationNumber);
            requestRulePageDTO.setProductNumber(productNumber);
            requestRulePageDTO.setPage(page);
            requestRulePageDTO.setRows(rows);
            requestRulePageDTO.setTenantId(tenantId);
            requestRulePageDTO.setRuleId(ruleId);
            // 获取规则集下的所有规则
            TxnPage<RuleRes> txnPage = ruleService.getPageByRuleType(requestRulePageDTO);
            result.setData(txnPage);
        } catch (TxnRuntimeException e) {
            result.setCode(e.getErrCode());
            result.setMessage(e.getErrMsg());
            logger.error(e.getMessage(), e);
        }
        logger.info("RuleController getPageByRuleSetTypeName end");
        return result;
    }
}
